package com.opdar.athena.support.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

/**
 * 功   能:
 * 创建者: 施俊帆
 * 日   期: 2014/11/17 1:35
 * Q  Q: 362116120
 */
public class NetTool {
    static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(NetTool.class);
    public synchronized static String post(String reqUrl, Map<String, Object> parameters) throws Exception{
        return new String(postBytes(reqUrl, parameters),"utf-8");
    }

    public synchronized static byte[] postBytes(String reqUrl, Map<String, Object> parameters) throws Exception{
        HttpURLConnection urlConn = null;
        String responseContent = null;
        try {
            StringBuffer params = new StringBuffer();
            for (Iterator iter = parameters.keySet().iterator(); iter.hasNext();) {
                String key =  (String) iter.next();
                Object value = parameters.get(key);
                if (value == null ) {
                    continue;
                }
                params.append(key.toString());
                params.append("=");
                params.append(URLEncoder.encode(value.toString(), "UTF-8"));
                params.append("&");
            }
            logger.info(reqUrl.concat("?").concat(params.toString()));
            URL url = new URL(reqUrl);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setRequestMethod("POST");
            urlConn.setConnectTimeout(5000);
            urlConn.setReadTimeout(5000);
            urlConn.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            urlConn.getOutputStream().write(b, 0, b.length);
            urlConn.getOutputStream().flush();
            urlConn.getOutputStream().close();

            InputStream in = urlConn.getInputStream();
            return read(in);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConn != null) {
                urlConn.disconnect();
            }
        }
        return null;
    }


    public static byte[] read(InputStream inputStream) throws IOException {
        ByteArrayOutputStream arrayBuffer = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len = -1;
        while ((len = inputStream.read(b)) != -1) {
            arrayBuffer.write(b, 0, len);
        }
        inputStream.close();
        arrayBuffer.close();
        return arrayBuffer.toByteArray();
    }
}
